using System.Collections;
using ProtoModels;
using UnityEngine;

public class SnapshotSyncManager : BehaviourSingletonInit<SnapshotSyncManager>
{
	public delegate void OnNotifyCloudSyncFinshed();

	public bool canSync = true;

	private bool hasInitialisedSync;

	public bool syncOnQuit = true;

	private StartupPanelController startup
	{
		get
		{
			TableTennisMainNavigation tableTennisMainNavigation = NavigationManager.instance as TableTennisMainNavigation;
			if (tableTennisMainNavigation == null)
			{
				return null;
			}
			return tableTennisMainNavigation.startupLayer;
		}
	}

	public bool syncInProgress { get; private set; }

	public override void Init()
	{
		hasInitialisedSync = false;
		syncOnQuit = true;
		syncInProgress = false;
		GGSnapshotCloudSync gGSnapshotCloudSync = GGFileIOCloudSync.instance as GGSnapshotCloudSync;
		if (gGSnapshotCloudSync != null)
		{
			gGSnapshotCloudSync.onConflict -= OnConflict;
			gGSnapshotCloudSync.onConflict += OnConflict;
		}
		GGApplication.OnQuitBehaviour onQuit = new GGApplication.OnQuitBehaviour();
		onQuit.isFinished = false;
		onQuit.action = delegate
		{
			GGOnApplicationQuit(delegate
			{
				onQuit.isFinished = true;
			});
		};
		BehaviourSingleton<GGApplication>.instance.AddOnQuitBehaviour(onQuit);
	}

	public void DoInitialSync(bool reloadActiveLayerOnExit = false)
	{
		if (syncInProgress)
		{
			return;
		}
		Debug.Log("DoInitialSync");
		GGSnapshotCloudSync gGSnapshotCloudSync = GGFileIOCloudSync.instance as GGSnapshotCloudSync;
		if (hasInitialisedSync || gGSnapshotCloudSync == null)
		{
			if (reloadActiveLayerOnExit)
			{
				NavigationManager.instance.ReloadActiveLayer();
			}
			return;
		}
		hasInitialisedSync = true;
		if (!GGPlayerSettings.instance.Model.canCloudSync)
		{
			if (reloadActiveLayerOnExit)
			{
				NavigationManager.instance.ReloadActiveLayer();
			}
		}
		else
		{
			syncInProgress = true;
			startup.Init();
			NavigationManager.instance.Push(startup.gameObject);
			gGSnapshotCloudSync.SynchronizeNow(OnInitialisationConflict);
		}
	}

	public void OnInitialisationConflict(GGServerRequestsBackend.ServerRequest request)
	{
		Debug.Log("on init sync finished");
		syncInProgress = false;
		GGServerRequestsBackend.CloudSyncRequest cloudSyncRequest = request as GGServerRequestsBackend.CloudSyncRequest;
		if (request.status != 0)
		{
			if (startup != null)
			{
				startup.DisplayCantReachServer();
			}
			return;
		}
		CloudSyncData response = request.GetResponse<CloudSyncData>();
		CloudSyncData.CloudSyncFile cloudSyncFile = null;
		foreach (CloudSyncData.CloudSyncFile file in response.files)
		{
			if (file.key == "player.bytes")
			{
				cloudSyncFile = file;
				break;
			}
		}
		if (cloudSyncFile != null)
		{
			PlayerModel model = new PlayerModel();
			if (!ProtoIO.LoadFromBase64String<PlayerModel>(cloudSyncFile.data, out model))
			{
				Debug.LogError("Can't deserialize model");
				if (startup != null)
				{
					startup.DisplayVersionOutOfDate();
				}
				return;
			}
			if (GGPlayerSettings.instance.Model.version < model.version)
			{
				if (startup != null)
				{
					startup.DisplayVersionOutOfDate();
				}
				return;
			}
		}
		if (startup != null)
		{
			startup.FinishStartup();
		}
		GGSnapshotCloudSync gGSnapshotCloudSync = GGFileIOCloudSync.instance as GGSnapshotCloudSync;
		gGSnapshotCloudSync.HandleSyncRequestResult(request);
		NavigationManager.instance.ReloadActiveLayer();
	}

	public void OnConflict(GGSnapshotCloudSync.CloudSyncConflict conflict)
	{
		StartCoroutine(DoOnConflict(conflict));
	}

	private IEnumerator DoOnConflict(GGSnapshotCloudSync.CloudSyncConflict conflict)
	{
		while (Application.loadedLevelName != ConfigBase.instance.menuSceneName)
		{
			yield return null;
		}
		TableTennisDialog.instance.ShowYesNo("Choose Cloud or Local Version", "There is previous progress stored in the cloud. Do you want to continue from your local progress or progress stored in the cloud?", "Cloud", "Local", delegate(bool complete)
		{
			NavigationManager.instance.Pop();
			GGSnapshotCloudSync gGSnapshotCloudSync = GGFileIOCloudSync.instance as GGSnapshotCloudSync;
			if (!(gGSnapshotCloudSync == null))
			{
				if (complete)
				{
					conflict.ResolveConflictUsingServerVersion();
					NavigationManager.instance.ReloadActiveLayer();
				}
				else
				{
					conflict.ResolveConflictUsingLocalVersion();
				}
			}
		});
	}

	private void GGOnApplicationQuit(OnNotifyCloudSyncFinshed onFinished = null)
	{
		Debug.Log("ForceSync - quit");
		GGSnapshotCloudSync gGSnapshotCloudSync = GGFileIOCloudSync.instance as GGSnapshotCloudSync;
		if (gGSnapshotCloudSync != null && syncOnQuit && GGPlayerSettings.instance.Model.canCloudSync)
		{
			gGSnapshotCloudSync.SynchronizeNow(delegate
			{
				Debug.Log("ForceSync sync finished");
				if (onFinished != null)
				{
					onFinished();
				}
			});
		}
		else if (onFinished != null)
		{
			onFinished();
		}
	}

	private void OnApplicationPause(bool pauseStatus)
	{
		if (Application.loadedLevelName != ConfigBase.instance.menuSceneName || MenuParameters.InitParameters.showTrainingTutorial || !canSync)
		{
			return;
		}
		if (pauseStatus)
		{
			GGSnapshotCloudSync gGSnapshotCloudSync = GGFileIOCloudSync.instance as GGSnapshotCloudSync;
			if (gGSnapshotCloudSync != null && syncOnQuit && GGPlayerSettings.instance.Model.canCloudSync)
			{
				gGSnapshotCloudSync.SynchronizeNow(gGSnapshotCloudSync.HandleSyncRequestResult);
			}
		}
		else if (!syncInProgress)
		{
			Init();
			DoInitialSync();
		}
	}

	public void OnFacebookLogin()
	{
		Debug.Log("SnapSyncManager - OnFacebookLogin");
		if (startup != null)
		{
			startup.LogIn();
			NavigationManager.instance.Push(startup.gameObject);
		}
	}

	public void OnFacebookLoginError(string msg)
	{
		Debug.Log("SnapSyncManager - OnFacebookLoginError");
		if (startup != null)
		{
			startup.FinishStartup();
			TableTennisDialog.instance.ShowOk("Facebook login failed!", "Facebook login failed! Please check your internet connection and try again!" + msg, "Ok", null);
		}
	}
}
